﻿using Microsoft.EntityFrameworkCore;
using S.PurchaseAndSales.Domain.SqlServer;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace S.PurchaseAndSales.Infrastructure
{
    public class BaseRepository<T> : IBaseRepository<T> where T : class
    {
        public SqlDbContext db { get; }

        public BaseRepository(SqlDbContext db)
        {
            this.db = db;
        }
        #region 异步增删改查方法
        public async Task<bool> AddAsync(T t)
        {
            db.Set<T>().AddAsync(t);
            return await db.SaveChangesAsync() > 0;
        }

        public async Task<bool> DeleteAsync(int id)
        {
            var list = await db.Set<T>().FindAsync(id);
            db.Set<T>().Remove(list);
            return await db.SaveChangesAsync() > 0;
        }

        public async Task<bool> UpdateAsync(T t)
        {
            db.Set<T>().Update(t);
            return await db.SaveChangesAsync() > 0;
        }

        public async Task<List<T>> GetAllAsync()
        {
            return await db.Set<T>().ToListAsync();
        }

        public async Task<T> GetByIdAsync(int id)
        {
            return await db.Set<T>().FindAsync(id);
        }
        #endregion
    }
}
